from celery import task
from yisheng.models import User_Sites, User, Contract
from company_manage.models import YsbCompanyInfo, BaiduAppCompanyInfo, ClarkiiSeoCompanyInfo, \
    SmsCompanyInfo, AllCompanyInfo
from clarkii_seo.models import SeoSysUser, SeoUserBusiness
from baidu_app.models import Company_Backup
from sms_company.models import FormCustomer
import re
from django.db.models import Q
import datetime
from dateutil.relativedelta import relativedelta
import logging
from util import getNeedData, getConstantsUtil
phone_pat = re.compile('^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$')

@task
def TestTask():
    logging.info('----------测试定时任务输出----------------------')

@task
def GetYSBCompanyInfoTask():
    logging.info(str(datetime.datetime.now()) + "获取易数宝公司资料开始")
    SaveYsb(phone_pat)
    logging.info(str(datetime.datetime.now()) + "获取易数宝公司资料结束")

@task
def GetBaiDuAPPCompanyInfoTask():
    logging.info(str(datetime.datetime.now()) + "获取百度商业平台公司信息开始")
    SaveBaiduApp(phone_pat)
    logging.info(str(datetime.datetime.now()) + "获取百度商业平台公司信息结束")

@task
def GetClarkiiSEOCompanyInfoTask():
    logging.info(str(datetime.datetime.now()) + "获取seo公司信息开始")
    SaveClsrkiiSeo(phone_pat)
    logging.info(str(datetime.datetime.now()) + "获取seo公司信息结束")

@task
def GetSmsCompanyInfoTask():
    logging.info(str(datetime.datetime.now()) + "获取sms公司信息开始")
    SaveSmsCompany()
    logging.info(str(datetime.datetime.now()) + "获取sms公司信息结束")

def SaveYsb(phone_pat):
    userList = User.objects.using('formal_ysb').values('id', 'company_name', 'mobile')
    saveList = []
    mobileStr = ""
    for user in userList:
        contract = Contract.objects.using('formal_ysb').values('sign_date', 'expire_date', 'service_cycle',
                                                               'service_price',
                                                               'ad_online_date', 'ad_offline_date').filter(
            user_id_back=user['id'])
        ysbCompanyInfo = YsbCompanyInfo()
        ysbCompanyInfo.user_id = user['id']
        if (user['company_name'] != None):
            if ("原昇" in user['company_name'] or "测试" in user['company_name'] or "test" in user['company_name']):
                continue
            else:
                ysbCompanyInfo.company_name = user['company_name']

        if (user['mobile'] == None):
            continue
        elif (user['mobile'] != None):
            userMobile = user['mobile'].strip().replace("\n", "").replace("\t", "")
            res = re.search(phone_pat, userMobile)
            if res == None or userMobile in mobileStr:
                continue
            mobileStr = mobileStr + userMobile +","
            ysbCompanyInfo.mobile = userMobile
        if (len(contract) > 0):
            for c in contract:
                ysbCompanyInfo.sign_date = c['sign_date']
                if (c['expire_date'] != None):
                    ysbCompanyInfo.expire_date = c['expire_date']
                    ysbCompanyInfo.service_cycle = c['service_cycle']
                    ysbCompanyInfo.service_price = c['service_price']
                if (c['ad_online_date'] != None):
                    ysbCompanyInfo.ad_online_date = c['ad_online_date']
                if (c['ad_offline_date'] != None):
                    ysbCompanyInfo.ad_offline_date = c['ad_offline_date']

        saveList.append(ysbCompanyInfo)
    YsbCompanyInfo.objects.all().delete()
    result = YsbCompanyInfo.objects.bulk_create(saveList)
    return result


def SaveBaiduApp(phone_pat):
    saveList = []
    mobileStr = ""
    companyBackupList = Company_Backup.objects.using("formal_kad").all()
    for companyInfo in companyBackupList:
        if ("原昇" in companyInfo.company_name or "测试" in companyInfo.company_name or "test" in companyInfo.company_name):
            continue
        phone_number = companyInfo.phone_number.strip().replace("\n", "").replace("\t", "")
        res = re.search(phone_pat,phone_number)
        if res == None or phone_number in mobileStr:
            continue
        mobileStr = mobileStr + phone_number +","
        baiduAppCompanyInfo = BaiduAppCompanyInfo()
        baiduAppCompanyInfo.user_id = companyInfo.user_id
        baiduAppCompanyInfo.company_name = companyInfo.company_name
        baiduAppCompanyInfo.phone_number = companyInfo.phone_number.replace(' ', '').replace("\n", "")
        baiduAppCompanyInfo.create_time = companyInfo.create_time
        baiduAppCompanyInfo.visit_time = companyInfo.visit_time
        if (companyInfo.app_id == 1):
            baiduAppCompanyInfo.app_name = '原力提词'
        elif (companyInfo.app_id == 2):
            baiduAppCompanyInfo.app_name = '原力创意'
        elif (companyInfo.app_id == 3):
            baiduAppCompanyInfo.app_name = '原力防护'

        saveList.append(baiduAppCompanyInfo)
    BaiduAppCompanyInfo.objects.all().delete()
    BaiduAppCompanyInfo.objects.bulk_create(saveList)  # 批量存入


def SaveClsrkiiSeo(phone_pat):
    saveList = []
    mobileStr = ""
    seoUserBusiness = SeoUserBusiness.objects.using('formal_seo').all()
    for userBussiness in seoUserBusiness:
        seoSysUser = SeoSysUser.objects.using('formal_seo').filter(user_id=userBussiness.sys_user_id)
        if (len(seoSysUser) < 1):
            continue
        if (seoSysUser[0].mobile == "" or seoSysUser[0].mobile == None):
            continue
        if ("原昇" in userBussiness.company or "测试" in userBussiness.company or "test" in userBussiness.company):
            continue
        mobile = seoSysUser[0].mobile.strip().replace("\n", "").replace("\t", "")
        res = re.search(phone_pat,mobile)
        if res == None or mobile in mobileStr:
            continue
        mobileStr = mobileStr +","
        clarkiiSeoCompanyInfo = ClarkiiSeoCompanyInfo()
        clarkiiSeoCompanyInfo.user_id = userBussiness.sys_user_id
        clarkiiSeoCompanyInfo.company = userBussiness.company
        clarkiiSeoCompanyInfo.start_time = userBussiness.start_time
        clarkiiSeoCompanyInfo.end_time = userBussiness.end_time
        clarkiiSeoCompanyInfo.industry = userBussiness.industry
        clarkiiSeoCompanyInfo.mainBussiness = userBussiness.mainBussiness
        clarkiiSeoCompanyInfo.mobile = seoSysUser[0].mobile.strip().replace("\n", "").replace("\t", "")
        saveList.append(clarkiiSeoCompanyInfo)
    ClarkiiSeoCompanyInfo.objects.all().delete()
    ClarkiiSeoCompanyInfo.objects.bulk_create(saveList)

def get_today():
    today = datetime.date.today()
    return today

def true_month_handle(datetime_now, num):
    datetime_month_ago = datetime_now - relativedelta(months=num)
    strArrays = str(datetime_month_ago).split('-')
    year_month = strArrays[0] + '-' + strArrays[1]
    day = strArrays[2].split(' ')[0]
    return year_month + '-' + day

def setCompanyInfo(formCustomer, smsCompanyInfo, phone):
    smsCompanyInfo.company_name = formCustomer.company_name
    smsCompanyInfo.url = formCustomer.url
    smsCompanyInfo.phone = phone
    smsCompanyInfo.city = formCustomer.city
    smsCompanyInfo.create_time = formCustomer.create_time
    smsCompanyInfo.update_time = formCustomer.update_time
    smsCompanyInfo.keyword = formCustomer.keyword
    smsCompanyInfo.discover_time = formCustomer.discover_time
    smsCompanyInfo.discover_count = formCustomer.discover_count
    return smsCompanyInfo

def SaveSmsCompany():
    saveList = []
    regex = r"(13[0-9]\d{8})|(14[5,7]\d{8})|(15[0-3,5-9]\d{8})|(18[0-2,5-9]\d{8})|(17[3,7]\d{8})"
    citys = getNeedData.getHandleCityList()
    date_from = '2017-01-01 00:00:00'
    handleMonth = getNeedData.getHandleMonth()
    date_from_two = str(true_month_handle(datetime.datetime.now(), int(handleMonth)))
    date_to_two = get_today()
    formCustomers = None
    if 'allCity' in citys:
        formCustomers = FormCustomer.objects.using('formal_sms').filter(Q(discover_time__range=(date_from_two, date_to_two)),
                                    Q(create_time__range=(date_from, date_to_two)) | Q(create_time__isnull=True),
                                    sem_status=0, aike_status=0).order_by('randid')
    else:
        formCustomers = FormCustomer.objects.using('formal_sms').filter(Q(city__in=citys), Q(discover_time__range=(date_from_two, date_to_two)),
                                                                        Q(create_time__range=(date_from, date_to_two)) | Q(create_time__isnull=True),
                                                                        sem_status=0, aike_status=0).order_by('randid')
    for formCustomer in formCustomers:
        phone = formCustomer.phone
        remark = formCustomer.remark
        smsCompanyInfo = SmsCompanyInfo()
        handlePhone = None
        if phone:
            groups = re.findall(regex, phone.replace(" ", ""))
            if groups:
                for group in groups:
                    if group:
                        handlePhone = ''.join(group)
                        continue
            if handlePhone and len(handlePhone) == 11 and ',' not in handlePhone:
                smsCompanyInfo_one = setCompanyInfo(formCustomer, smsCompanyInfo, handlePhone)
                saveList.append(smsCompanyInfo_one)
        elif remark:
            groups = re.findall(regex, remark.replace(" ", ""))
            if groups:
                for group in groups:
                    if group:
                        handlePhone = ''.join(group)
                        continue
            if handlePhone and len(handlePhone) == 11 and ',' not in handlePhone:
                smsCompanyInfo_one = setCompanyInfo(formCustomer, smsCompanyInfo, handlePhone)
                saveList.append(smsCompanyInfo_one)
    SmsCompanyInfo.objects.all().delete()
    SmsCompanyInfo.objects.bulk_create(saveList)

@task
def getAllCompanyInfoTask():
    logging.info(str(datetime.datetime.now()) + "获取指定平台公司信息开始")
    string = getConstantsUtil.getConstantsValeORDeault('handleCompany', 'SMS,BaiDu')
    AllCompanyInfo.objects.all().delete()

    for s in string.split(','):
        if 'SMS' == s:
            logging.info(str(datetime.datetime.now()) + "处理SMS公司信息")
            saveList = []
            sms_qs = SmsCompanyInfo.objects.exclude(phone="")
            for sms in sms_qs:
                allCompanyInfo = AllCompanyInfo()
                allCompanyInfo.company_name = sms.company_name
                allCompanyInfo.phone = sms.phone
                allCompanyInfo.source = 'SMS'
                saveList.append(allCompanyInfo)
            AllCompanyInfo.objects.bulk_create(saveList)
        if 'BaiDu' == s:
            logging.info(str(datetime.datetime.now()) + "处理百度商业应用公司信息")
            saveList = []
            baidu_qs = BaiduAppCompanyInfo.objects.exclude(phone_number="")
            for baidu in baidu_qs:
                allCompanyInfo = AllCompanyInfo()
                allCompanyInfo.company_name = baidu.company_name
                allCompanyInfo.phone = baidu.phone_number
                allCompanyInfo.source = '百度商业应用'
                saveList.append(allCompanyInfo)
            AllCompanyInfo.objects.bulk_create(saveList)
        if 'ClarkiiSEO' == s:
            logging.info(str(datetime.datetime.now()) + "处理ClarkiiSEO公司信息")
            saveList = []
            clarkiiseo_qs = ClarkiiSeoCompanyInfo.objects.exclude(mobile="")
            for clarkiiseo in clarkiiseo_qs:
                allCompanyInfo = AllCompanyInfo()
                allCompanyInfo.company_name = clarkiiseo.company
                allCompanyInfo.phone = clarkiiseo.mobile
                allCompanyInfo.source = 'ClarkiiSEO'
                saveList.append(allCompanyInfo)
            AllCompanyInfo.objects.bulk_create(saveList)
        if 'YSB' == s:
            logging.info(str(datetime.datetime.now()) + "处理易数宝公司信息")
            saveList = []
            ysb_qs = YsbCompanyInfo.objects.exclude(mobile="")
            for ysb in ysb_qs:
                allCompanyInfo = AllCompanyInfo()
                allCompanyInfo.company_name = ysb.company_name
                allCompanyInfo.phone = ysb.mobile
                allCompanyInfo.source = '易数宝'
                saveList.append(allCompanyInfo)
            AllCompanyInfo.objects.bulk_create(saveList)
    logging.info(str(datetime.datetime.now()) + "获取指定平台公司信息结束")
